package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Autism
 * @version V1.0
 * @Package com.itheima.service
 * @date 2019/7/31 21:42
 * @Description
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    OrderSettingDao orderSettingDao;

    /**
     * 上传文件
     *
     * @param ordersettingList
     */
    @Override
    public void upload(List<OrderSetting> ordersettingList) {
        if (!CollectionUtils.isEmpty(ordersettingList)) {
            ordersettingList.forEach(item -> {
                addOrUpdateByOrderDate(item);
            });
        }
    }

    /**
     * 获取日历显示数据
     *
     * @param date
     * @return
     */
    @Override
    public List<Map> getCalenderData(String date) {
        List<Map> result = new ArrayList<>();
        //date 2019-7
        // 生成第一天字符串
        String start = date + "-1"; //2019-7-1
        //生成最后一天字符串
        String end = date + "-31"; //2019-7-31
        List<OrderSetting> orderSettingList = orderSettingDao.getCalenderData(start, end);
        //{ date: 1, number: 120, reservations: 1 },
        if (!CollectionUtils.isEmpty(orderSettingList)) {
            orderSettingList.forEach(item->{
                Map map = new HashMap<String, Integer>();
                map.put("date", item.getOrderDate().getDate());
                map.put("number", item.getNumber());
                map.put("reservations", item.getReservations());
                result.add(map);
            });
        }
        return result;
    }

    /**
     * 根据日期设置可预约人数
     * @param orderSetting
     */
    @Override
    public void setDataByOrderDate(OrderSetting orderSetting) {
        addOrUpdateByOrderDate(orderSetting);
    }

    //TODO:修改可预约人数之后不能刷新回显修改过的人数,待修改

    /**
     * 根据日期设置可预约人数
     * @param item
     */
    private void addOrUpdateByOrderDate(OrderSetting item) {
        //查询数据库里同一天的记录有没有
        long count = orderSettingDao.findCountByOrderDate(item.getOrderDate());
        if (count > 0) {
            //如果没有就更新
            orderSettingDao.updateNumberByOrderDate(item);
        } else {
            //如果没有,新增
            orderSettingDao.add(item);
        }
    }
}
